package com.gckj.dfds.backup;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description:
 * @Author liu Weidong
 * @Email:
 * @Date: 2024/5/9 15:01
 * @Version 1.0
 */
public class FsImageTransfer extends Thread{
    private SocketChannel socketChannel;
    private static final String HOST = "127.0.0.1";
    private static final Integer PORT = 60006;
    private Selector selector;
    private FsImage fsImage;

    public FsImageTransfer(FsImage fsImage){
        init();
        this.fsImage = fsImage;
    }

    @Override
    public void run() {
        try {
            this.uploadFsImage();
            boolean uploadFlag = true;
            while (uploadFlag) {
                int select = selector.select();
                // 有可以用的通道
                if (select > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isReadable()) {
                            SocketChannel channel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            int count = channel.read(byteBuffer);
                            String result = new String(byteBuffer.array(),0,count);
                            System.out.println("上传fsImage后namenode返回结果："+result);
                            uploadFlag = false;
                            channel.close();
                        }
                        iterator.remove();
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    public void init(){
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向nameNode发送fsImage
     */
    public void uploadFsImage(){
        ByteBuffer wrap = ByteBuffer.wrap(fsImage.getFsImageJson().getBytes(StandardCharsets.UTF_8));
        try {
            socketChannel.write(wrap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
